import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Typography,
  Row,
  Col,
  Statistic,
  DatePicker,
  Select,
  Input,
  Modal,
  Badge,
  Tooltip,
  Divider,
  Alert,
  Drawer,
  Timeline,
  Progress
} from 'antd';
import {
  ReloadOutlined,
  SearchOutlined,
  EyeOutlined,
  DownloadOutlined,
  FilterOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import { api } from '@/services/api';
import FieldDiffViewer from '@/components/FieldDiffViewer';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';

const { Text, Title } = Typography;
const { RangePicker } = DatePicker;
const { Option } = Select;

interface RequestLog {
  id: number;
  requestId: string;
  userId?: string;
  userIp?: string;
  status: 'success' | 'error' | 'in_progress' | 'timeout';
  currentPhase: 'client_request' | 'copilot_request' | 'copilot_response' | 'client_response';
  modelName?: string;
  isStreaming: boolean;
  hasTools: boolean;
  totalDuration?: number;
  errorMessage?: string;
  createdAt: string;
  updatedAt: string;
  summary: {
    isCompleted: boolean;
    performance: {
      totalDuration?: number;
      conversionDuration?: number;
      apiDuration?: number;
      inputTokens?: number;
      outputTokens?: number;
      retryCount: number;
    };
    error?: {
      phase: string;
      message: string;
      hasStack: boolean;
    };
    timeline: Array<{
      phase: string;
      time: string;
      duration?: number;
    }>;
  };
}

interface LogStatistics {
  totalRequests: number;
  successRequests: number;
  errorRequests: number;
  averageResponseTime: number;
  successRate: number;
  errorRate: number;
  totalTokensUsed: number;
  topErrors: Array<{ message: string; count: number }>;
}

const CopilotLogs: React.FC = () => {
  const [logs, setLogs] = useState<RequestLog[]>([]);
  const [statistics, setStatistics] = useState<LogStatistics | null>(null);
  const [loading, setLoading] = useState(false);
  const [selectedLog, setSelectedLog] = useState<RequestLog | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [fieldMappingsVisible, setFieldMappingsVisible] = useState(false);
  const [fieldMappings, setFieldMappings] = useState<any>(null);
  
  // 筛选条件
  const [filters, setFilters] = useState({
    page: 1,
    pageSize: 20,
    status: undefined as string | undefined,
    dateRange: null as [dayjs.Dayjs, dayjs.Dayjs] | null,
    search: '',
    userId: undefined as string | undefined
  });
  
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });

  // 加载日志列表
  const loadLogs = useCallback(async () => {
    try {
      setLoading(true);
      const params: any = {
        page: filters.page,
        pageSize: filters.pageSize
      };

      if (filters.status) params.status = filters.status;
      if (filters.search) params.search = filters.search;
      if (filters.userId) params.userId = filters.userId;
      if (filters.dateRange) {
        params.startTime = filters.dateRange[0].toISOString();
        params.endTime = filters.dateRange[1].toISOString();
      }

      const response = await api.get('/api/v1/copilot/logs', { params });
      
      if (response.data.success) {
        setLogs(response.data.data.data);
        setPagination({
          current: response.data.data.page,
          pageSize: response.data.data.pageSize,
          total: response.data.data.total
        });
      }
    } catch (error) {
      console.error('Failed to load logs:', error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  // 加载统计信息
  const loadStatistics = useCallback(async () => {
    try {
      const params: any = {};
      if (filters.dateRange) {
        params.startTime = filters.dateRange[0].toISOString();
        params.endTime = filters.dateRange[1].toISOString();
      }

      const response = await api.get('/api/v1/copilot/logs/statistics/overview', { params });
      
      if (response.data.success) {
        setStatistics(response.data.data);
      }
    } catch (error) {
      console.error('Failed to load statistics:', error);
    }
  }, [filters.dateRange]);

  // 加载字段映射信息
  const loadFieldMappings = async (requestId: string) => {
    try {
      const response = await api.get(`/api/v1/copilot/logs/${requestId}/field-mappings`);
      
      if (response.data.success) {
        setFieldMappings(response.data.data);
      }
    } catch (error) {
      console.error('Failed to load field mappings:', error);
    }
  };

  useEffect(() => {
    loadLogs();
    loadStatistics();
  }, [loadLogs, loadStatistics]);

  // 状态颜色映射
  const getStatusColor = (status: string) => {
    const colors = {
      success: 'success',
      error: 'error',
      in_progress: 'processing',
      timeout: 'warning'
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  // 状态文本映射
  const getStatusText = (status: string) => {
    const texts = {
      success: '成功',
      error: '错误',
      in_progress: '进行中',
      timeout: '超时'
    };
    return texts[status as keyof typeof texts] || status;
  };

  // 阶段文本映射
  const getPhaseText = (phase: string) => {
    const texts = {
      client_request: '客户端请求',
      copilot_request: 'Copilot请求',
      copilot_response: 'Copilot响应',
      client_response: '客户端响应'
    };
    return texts[phase as keyof typeof texts] || phase;
  };

  // 表格列定义
  const columns: ColumnsType<RequestLog> = [
    {
      title: '请求ID',
      dataIndex: 'requestId',
      key: 'requestId',
      width: 120,
      render: (text: string) => (
        <Text code style={{ fontSize: '12px' }}>
          {text.substring(0, 8)}...
        </Text>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: string, record: RequestLog) => (
        <Space direction="vertical" size={2}>
          <Tag color={getStatusColor(status)}>
            {getStatusText(status)}
          </Tag>
          <Text type="secondary" style={{ fontSize: '11px' }}>
            {getPhaseText(record.currentPhase)}
          </Text>
        </Space>
      )
    },
    {
      title: '模型',
      dataIndex: 'modelName',
      key: 'modelName',
      width: 120,
      render: (text: string) => text || '-'
    },
    {
      title: '用户',
      dataIndex: 'userId',
      key: 'userId',
      width: 100,
      render: (text: string) => text || '-'
    },
    {
      title: '性能',
      key: 'performance',
      width: 120,
      render: (_, record: RequestLog) => (
        <Space direction="vertical" size={2}>
          <Text style={{ fontSize: '12px' }}>
            {record.summary.performance.totalDuration 
              ? `${record.summary.performance.totalDuration}ms` 
              : '-'
            }
          </Text>
          {record.summary.performance.inputTokens && (
            <Text type="secondary" style={{ fontSize: '11px' }}>
              {record.summary.performance.inputTokens}↑/{record.summary.performance.outputTokens}↓
            </Text>
          )}
        </Space>
      )
    },
    {
      title: '特征',
      key: 'features',
      width: 80,
      render: (_, record: RequestLog) => (
        <Space>
          {record.isStreaming && (
            <Tooltip title="流式响应">
              <Badge status="processing" />
            </Tooltip>
          )}
          {record.hasTools && (
            <Tooltip title="使用工具">
              <Badge status="success" />
            </Tooltip>
          )}
          {record.summary.performance.retryCount > 0 && (
            <Tooltip title={`重试 ${record.summary.performance.retryCount} 次`}>
              <Badge status="warning" />
            </Tooltip>
          )}
        </Space>
      )
    },
    {
      title: '时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
      render: (text: string) => (
        <Space direction="vertical" size={2}>
          <Text style={{ fontSize: '12px' }}>
            {dayjs(text).format('MM-DD HH:mm:ss')}
          </Text>
          <Text type="secondary" style={{ fontSize: '11px' }}>
            {dayjs(text).fromNow()}
          </Text>
        </Space>
      )
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_, record: RequestLog) => (
        <Space>
          <Button 
            type="link" 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => {
              setSelectedLog(record);
              setDetailModalVisible(true);
            }}
          >
            详情
          </Button>
          <Button 
            type="link" 
            size="small"
            onClick={() => {
              setSelectedLog(record);
              loadFieldMappings(record.requestId);
              setFieldMappingsVisible(true);
            }}
          >
            映射
          </Button>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>
        <Space>
          <ClockCircleOutlined />
          Copilot 请求日志
        </Space>
      </Title>

      {/* 统计概览 */}
      {statistics && (
        <Card style={{ marginBottom: 24 }}>
          <Row gutter={16}>
            <Col span={4}>
              <Statistic 
                title="总请求数" 
                value={statistics.totalRequests}
                prefix={<InfoCircleOutlined />}
              />
            </Col>
            <Col span={4}>
              <Statistic 
                title="成功率" 
                value={statistics.successRate}
                suffix="%"
                valueStyle={{ color: statistics.successRate > 95 ? '#3f8600' : '#cf1322' }}
                prefix={<CheckCircleOutlined />}
              />
            </Col>
            <Col span={4}>
              <Statistic 
                title="平均响应时间" 
                value={statistics.averageResponseTime}
                suffix="ms"
                prefix={<ClockCircleOutlined />}
              />
            </Col>
            <Col span={4}>
              <Statistic 
                title="Token使用量" 
                value={statistics.totalTokensUsed}
                formatter={(value) => `${Number(value).toLocaleString()}`}
              />
            </Col>
            <Col span={4}>
              <Statistic 
                title="错误请求" 
                value={statistics.errorRequests}
                valueStyle={{ color: statistics.errorRequests > 0 ? '#cf1322' : '#3f8600' }}
                prefix={<ExclamationCircleOutlined />}
              />
            </Col>
            <Col span={4}>
              <Progress 
                type="dashboard" 
                percent={statistics.successRate}
                width={80}
                format={(percent) => `${percent}%`}
              />
            </Col>
          </Row>
        </Card>
      )}

      {/* 筛选工具栏 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <RangePicker 
              style={{ width: '100%' }}
              showTime
              value={filters.dateRange}
              onChange={(dates) => setFilters({ ...filters, dateRange: dates, page: 1 })}
              placeholder={['开始时间', '结束时间']}
            />
          </Col>
          <Col span={3}>
            <Select 
              style={{ width: '100%' }}
              placeholder="状态筛选"
              allowClear
              value={filters.status}
              onChange={(value) => setFilters({ ...filters, status: value, page: 1 })}
            >
              <Option value="success">成功</Option>
              <Option value="error">错误</Option>
              <Option value="in_progress">进行中</Option>
              <Option value="timeout">超时</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Input
              placeholder="搜索请求ID、用户ID、错误信息"
              prefix={<SearchOutlined />}
              value={filters.search}
              onChange={(e) => setFilters({ ...filters, search: e.target.value })}
              onPressEnter={() => setFilters({ ...filters, page: 1 })}
            />
          </Col>
          <Col span={3}>
            <Input
              placeholder="用户ID"
              value={filters.userId}
              onChange={(e) => setFilters({ ...filters, userId: e.target.value })}
              onPressEnter={() => setFilters({ ...filters, page: 1 })}
            />
          </Col>
          <Col span={8}>
            <Space>
              <Button 
                type="primary" 
                icon={<FilterOutlined />}
                onClick={() => setFilters({ ...filters, page: 1 })}
              >
                应用筛选
              </Button>
              <Button 
                icon={<ReloadOutlined />}
                onClick={() => {
                  loadLogs();
                  loadStatistics();
                }}
                loading={loading}
              >
                刷新
              </Button>
              <Button 
                icon={<DownloadOutlined />}
                onClick={() => {
                  // TODO: 实现导出功能
                  alert('导出功能开发中');
                }}
              >
                导出
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 错误概览 */}
      {statistics?.topErrors && statistics.topErrors.length > 0 && (
        <Alert
          style={{ marginBottom: 24 }}
          type="warning"
          showIcon
          message="常见错误"
          description={
            <div>
              {statistics.topErrors.slice(0, 3).map((error, index) => (
                <div key={index} style={{ marginBottom: 4 }}>
                  <Tag color="orange">{error.count}</Tag>
                  <Text>{error.message}</Text>
                </div>
              ))}
            </div>
          }
          closable
        />
      )}

      {/* 主表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={logs}
          loading={loading}
          rowKey="id"
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
            onChange: (page, pageSize) => {
              setFilters({ ...filters, page, pageSize });
            }
          }}
          scroll={{ x: 1000 }}
          size="small"
        />
      </Card>

      {/* 详情弹窗 */}
      <Modal
        title="请求详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        width={800}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {selectedLog && (
          <div>
            <Row gutter={16}>
              <Col span={12}>
                <Card size="small" title="基础信息">
                  <p><strong>请求ID:</strong> <Text code>{selectedLog.requestId}</Text></p>
                  <p><strong>状态:</strong> <Tag color={getStatusColor(selectedLog.status)}>{getStatusText(selectedLog.status)}</Tag></p>
                  <p><strong>当前阶段:</strong> {getPhaseText(selectedLog.currentPhase)}</p>
                  <p><strong>模型:</strong> {selectedLog.modelName || '-'}</p>
                  <p><strong>用户:</strong> {selectedLog.userId || '-'}</p>
                  <p><strong>IP:</strong> {selectedLog.userIp || '-'}</p>
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small" title="性能指标">
                  <p><strong>总耗时:</strong> {selectedLog.summary.performance.totalDuration || '-'}ms</p>
                  <p><strong>转换耗时:</strong> {selectedLog.summary.performance.conversionDuration || '-'}ms</p>
                  <p><strong>API耗时:</strong> {selectedLog.summary.performance.apiDuration || '-'}ms</p>
                  <p><strong>输入Token:</strong> {selectedLog.summary.performance.inputTokens || '-'}</p>
                  <p><strong>输出Token:</strong> {selectedLog.summary.performance.outputTokens || '-'}</p>
                  <p><strong>重试次数:</strong> {selectedLog.summary.performance.retryCount}</p>
                </Card>
              </Col>
            </Row>

            <Divider />

            <Card size="small" title="请求时间线">
              <Timeline
                items={selectedLog.summary.timeline.map(item => ({
                  children: (
                    <div>
                      <Text strong>{getPhaseText(item.phase)}</Text>
                      <br />
                      <Text type="secondary">{dayjs(item.time).format('HH:mm:ss.SSS')}</Text>
                      {item.duration && <Text type="secondary"> (+{item.duration}ms)</Text>}
                    </div>
                  )
                }))}
              />
            </Card>

            {selectedLog.summary.error && (
              <>
                <Divider />
                <Alert
                  type="error"
                  showIcon
                  message={`错误发生在: ${getPhaseText(selectedLog.summary.error.phase)}`}
                  description={selectedLog.summary.error.message}
                />
              </>
            )}
          </div>
        )}
      </Modal>

      {/* 字段映射弹窗 */}
      <Drawer
        title="字段映射分析"
        placement="right"
        onClose={() => setFieldMappingsVisible(false)}
        open={fieldMappingsVisible}
        width={720}
      >
        {fieldMappings && (
          <div>
            {/* 映射摘要 */}
            <Card size="small" title="变化摘要" style={{ marginBottom: 16 }}>
              <Row gutter={16}>
                <Col span={8}>
                  <Statistic title="总变化数" value={fieldMappings.changeSummary.totalChanges} />
                </Col>
                <Col span={8}>
                  <Statistic title="新增字段" value={fieldMappings.changeSummary.addedFields} />
                </Col>
                <Col span={8}>
                  <Statistic title="移除字段" value={fieldMappings.changeSummary.removedFields} />
                </Col>
              </Row>
            </Card>

            {/* 转换模式 */}
            <Card size="small" title="转换模式" style={{ marginBottom: 16 }}>
              <p><strong>模式:</strong> {fieldMappings.transformationPattern.description}</p>
              <p><strong>置信度:</strong> <Progress percent={fieldMappings.transformationPattern.confidence * 100} size="small" /></p>
            </Card>

            {/* 关键字段变化 */}
            {fieldMappings.changeSummary.criticalChanges.length > 0 && (
              <Alert
                type="warning"
                showIcon
                message="关键字段变化"
                description={fieldMappings.changeSummary.criticalChanges.join(', ')}
                style={{ marginBottom: 16 }}
              />
            )}

            {/* 字段差异可视化 */}
            <FieldDiffViewer
              mappings={Object.values(fieldMappings.groupedMappings).flat()}
              fromPhaseName="转换前"
              toPhaseName="转换后"
            />
          </div>
        )}
      </Drawer>
    </div>
  );
};

export default CopilotLogs;